<template>
<div class="background-image">
  <div class="chat-container">
    <h2>健康简单诊断问答</h2>
    <h5>Tips:请在联网的环境进行</h5>
    <div id="results">
      <button id="clear">清空对话</button>
      <textarea id="result"></textarea>
    </div>
    
    <div id="sendVal">
      <input id="question" type="text" placeholder="输入您的问题...">
      <button id="btn">发送信息</button>
    </div>
  </div>
</div>
</template>

<script>
import { onMounted } from 'vue';
import * as base64 from 'base-64';
import CryptoJs from 'crypto-js';

export default {
  name: 'ChatComponent',
  setup() {
    let questionInput;
    let sendMsgBtn;
    let result;
    let clear;

    const requestObj = {
      APPID: 'b8d4e8e0',
      APISecret: 'YjRiZDcwZTNjNTZmZWQ5MTRmYjU0NmVj',
      APIKey: '52b02c7d1a8b4b4371cf8ebc4e745439',
      Uid: "redrun",
      sparkResult: ''
    };

    const sendMsg = async () => {
      let myUrl = await getWebsocketUrl();
      let inputVal = questionInput.value;
      let socket = new WebSocket(myUrl);

      socket.addEventListener('open', (event) => {
        console.log('开启连接！！', event);
        let params = {
          "header": {
            "app_id": requestObj.APPID,
            "uid": "redrun"
          },
          "parameter": {
            "chat": {
              "domain": "lite",
              "temperature": 0.5,
              "max_tokens": 1024,
            }
          },
          "payload": {
            "message": {
              "text": [
                { "role": "user", "content": "你是谁" },
                { "role": "assistant", "content": "我是AI助手" },
                { "role": "user", "content": inputVal }
              ]
            }
          }
        };
        console.log("发送消息");
        socket.send(JSON.stringify(params));
      });

      socket.addEventListener('message', (event) => {
        let data = JSON.parse(event.data);
        requestObj.sparkResult += data.payload.choices.text[0].content;
        if (data.header.code !== 0) {
          console.log("出错了", data.header.code, ":", data.header.message);
          socket.close();
        }
        if (data.header.code === 0) {
          if (data.payload.choices.text && data.header.status === 2) {
            requestObj.sparkResult += data.payload.choices.text[0].content;
            setTimeout(() => {
              socket.close();
            }, 1000);
          }
        }
        addMsgToTextarea(requestObj.sparkResult);
      });

      socket.addEventListener('close', (event) => {
        console.log('连接关闭！！', event);
        requestObj.sparkResult += '\n'; // 在每次对话结束时添加换行符
        addMsgToTextarea(requestObj.sparkResult);
        questionInput.value = '';
      });

      socket.addEventListener('error', (event) => {
        console.log('连接发送错误！！', event);
      });
    };

    const getWebsocketUrl = () => {
      return new Promise((resolve, reject) => {
        let url = "wss://spark-api.xf-yun.com/v1.1/chat";
        let host = "spark-api.xf-yun.com";
        let apiKeyName = "api_key";
        let date = new Date().toGMTString();
        let algorithm = "hmac-sha256";
        let headers = "host date request-line";
        let signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`;
        let signatureSha = CryptoJs.HmacSHA256(signatureOrigin, requestObj.APISecret);
        let signature = CryptoJs.enc.Base64.stringify(signatureSha);
        let authorizationOrigin = `${apiKeyName}="${requestObj.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
        let authorization = base64.encode(authorizationOrigin);

        url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;
        resolve(url);
      });
    };

    const addMsgToTextarea = (text) => {
      result.value = text; // 使用 value 属性设置 textarea 内容
    };

    onMounted(() => {
      questionInput = document.querySelector("#question");
      sendMsgBtn = document.querySelector("#btn");
      result = document.querySelector("#result");
      clear = document.querySelector("#clear");

      // 点击发送信息按钮
      sendMsgBtn.addEventListener('click', () => {
        sendMsg();
      });

      // 点击清除对话按钮
      clear.addEventListener('click', () => {
        requestObj.sparkResult = ''; // 清空请求对象中的结果
        addMsgToTextarea(''); // 清空结果显示区域
      });

      // 输入完信息点击enter发送信息
      questionInput.addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
          event.preventDefault(); // 阻止默认行为，防止表单提交
          sendMsg();
        }
      });
    });
  }
};
</script>

<style>
.background-image{
  /* height:max;
  weight:max;

 background-image: url('../../assets/images/background.jpg'); */
}
.chat-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
  font-family: 'Arial', sans-serif;
}

h2 {
  margin: 0 0 10px;
  font-size: 36px;
  color: #3f51b5;
  font-weight: bold;
}

h3, h5 {
  font-size: 18px;
  margin: 0 0 10px;
  color: #616161;
}

#results {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}

#result {
  width: 100%;
  height: 60vh;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  resize: none;
  background-color: #f9f9f9;
  font-size: 18px; /* 增大字体大小 */
  line-height: 1.6; /* 增加行间距 */
  color: #333;
  white-space: pre-wrap;
  overflow: auto;
  font-family: 'Roboto', sans-serif; /* 更现代的字体 */
}

#sendVal {
  display: flex;
  align-items: center;
  margin-top: auto;
}

#question {
  flex: 1;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-right: 10px;
  font-size: 16px;
  color: #333;
}

#btn, #clear {
  padding: 10px 20px;
  background-color: #3f51b5;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

#btn:hover, #clear:hover {
  background-color: #303f9f;
}

#clear {
  margin-bottom: 5px;
}

/* 响应式布局 */
@media (max-width: 600px) {
  .chat-container {
    padding: 15px;
  }

  h2 {
    font-size: 28px;
  }

  h3, h5 {
    font-size: 16px;
  }

  #result {
    height: 50vh;
    font-size: 16px;
  }

  #question {
    font-size: 14px;
  }

  #btn, #clear {
    font-size: 14px;
  }
}
</style>